package com.aiju.base.activity;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.aiju.app.config.ConfigManager;
import com.aiju.base.R;
import com.aiju.common.ActivityStack;
import com.aiju.support.lifecycle.ActivityFragmentLifecycle;
import com.aiju.utils.AppUtil;
import com.aiju.utils.L;
import com.readystatesoftware.systembartint.SystemBarTintManager;

import java.util.List;

/**
 * @author: 佐为
 * @date: 2016-11-10 09:53
 * @version: V1.0
 * @Description: activity 第一层封装（基础层）。生命周期的打印、观察，触屏收缩键盘， 沉浸式标题栏
 */
public abstract class AbsActivity extends AppCompatActivity {

    private static long trigleCancel = 0;

    private static boolean isDebug = ConfigManager.DEBUG;

    protected SystemBarTintManager tintManager;

    private final ActivityFragmentLifecycle lifecycle = new ActivityFragmentLifecycle();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
        }


        setStatusBar();
        ActivityStack.push(this);
        log("onCreate()");
    }

    protected void setStatusBar() {
        tintManager = new SystemBarTintManager(this);
        tintManager.setStatusBarTintEnabled(true);
//        tintManager.setTintColor(getResources().getColor(R.color.color_30a3ff));
        tintManager.setTintResource(R.mipmap.status_bar);

    }

    @TargetApi(19)
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    @Override
    protected void onStart() {
        super.onStart();
        lifecycle.onStart();
        log("onStart()");
    }

    @Override
    protected void onResume() {
        super.onResume();
        AppUtil.currentActivity = this;
        log("onResume()");
    }

    @Override
    protected void onStop() {
        super.onStop();
        lifecycle.onStop();
        log("onStop()");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        log("onRestart()");
    }

    @Override
    protected void onDestroy() {
        ActivityStack.pop(this);
        super.onDestroy();
        lifecycle.onDestroy();
        log("onDestroy()");
    }

    /**
     * 按下按键时触发
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) { // 按了后退键
            onBackPressed();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        final List<AbsActivity> list = ActivityStack.getActivityList();
        if (list.size() > 1) {
            finish();
        } else {
            toastExtrance();
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View view = getCurrentFocus();
            if (isHideInput(view, ev)) {
                HideSoftInput(view.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 判定是否需要隐藏
     */
    private boolean isHideInput(View v, MotionEvent ev) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left
                    + v.getWidth();
            if (ev.getX() > left && ev.getX() < right && ev.getY() > top
                    && ev.getY() < bottom) {
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * 隐藏软键盘
     */
    private void HideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            manager.hideSoftInputFromWindow(token,
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 退出系统提示
     */
    private void toastExtrance() {
        final long uptimeMillis = SystemClock.uptimeMillis();
        if (uptimeMillis - trigleCancel > 2000) {
            trigleCancel = uptimeMillis;
            Toast.makeText(this, "再按一次退出!", Toast.LENGTH_SHORT).show();
        } else {
            exitApp();
        }
    }

    /**
     * 跳转页面
     *
     * @param clas
     */
    public void startActivity(Class<?> clas) {
        startActivity(new Intent(this, clas));
    }


    /**
     * 退出系统，清除资源
     */
    private void exitApp() {
        ActivityStack.finishAll();
    }

    public ActivityFragmentLifecycle getLifecycle() {
        return lifecycle;
    }

    /**
     * 打印日志
     *
     * @param msg
     */
    private void log(String msg) {
        if (isDebug) {
            L.d(ConfigManager.DEBUG_LIFECYCLE_TAG, getClass().getName() + ":" + msg);
        }
    }

}
